<template>
  <div class="home-page">
    <div class="header">
      <h1>应用列表</h1>
      <el-button @click="handleLogout">退出登录</el-button>
    </div>
    
    <div class="card-container" 
         v-loading="loading"
         @dragover.prevent="handleDragOver"
         @dragleave="handleDragLeave"
         @drop.prevent="handleDrop"
         :class="{ 'drag-active': isDragging }">
      <el-row :gutter="20">
        <el-col v-for="(app, index) in appList" 
                :key="index" 
                :xs="12" :sm="8" :md="6" :lg="4">
          <el-card class="app-card" shadow="hover" :body-style="{ height: '220px', padding: '15px' }">
            <div class="app-icon">
              <img :src="app.icon" alt="app icon" v-if="app.icon">
              <i class="el-icon-apple" v-else></i>
            </div>
            <div class="app-info">
              <div class="app-log">
                <el-image
                  style="width: 100px; height: 100px"
                  :src="baseUrl + '/api/v1/distribution/package/icon/' + app.pid"
                  :zoom-rate="1.2"
                  :max-scale="7"
                  :min-scale="0.2"
                  :preview-src-list="srcList"
                  :initial-index="4"
                  fit="cover"
                />
              </div>
              <div class="app-name">{{ app.name }}</div>
              <div class="app-meta">
                <div class="app-version">版本: {{ app.version || '1.0.0' }}</div>
                <div class="app-size">大小: {{ formatFileSize(app.size) }}</div>
                <div class="app-update-time">更新: {{ formatDate(app.updateTime) }}</div>
                <div class="app-platform">平台: {{ app.platform }}</div>
                <div class="app-bundleid" :title="app.bundleid">包名: {{ truncateText(app.bundleid, 35) }}</div>
                <div class="app-name">分享码:{{app.shortCode}}</div>
                <div class="app-actions">
                  <el-button type="primary" @click="onSubmit(app)">查看下载页</el-button>
                  <el-button type="danger" @click="handleDelete(app)" :loading="deleteLoading === app.id">删除</el-button>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :xs="12" :sm="8" :md="6" :lg="4">
          <el-card class="upload-card" shadow="hover" :body-style="{ height: '220px' }">
            <div class="upload-content">
              <el-upload
                class="upload-demo"
                drag
                :auto-upload="true"
                :show-file-list="false"
                :http-request="handleUpload"
                :before-upload="beforeUpload"
                :on-progress="handleProgress"
                accept=".apk,.ipa,.zip,.rar">
                <div class="upload-area">
                  <i class="el-icon-upload"></i>
                  <div class="upload-text">
                    <p v-if="appList.length === 0">暂无应用</p>
                    <p>拖拽文件到此处上传</p>
                    <p class="file-types">支持格式: APK/IPA/ZIP/RAR</p>
                  </div>
                  <el-progress 
                    v-if="uploadProgress > 0" 
                    :percentage="uploadProgress" 
                    :stroke-width="6"
                    :format="formatProgress"/>
                </div>
              </el-upload>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"/>
    </div>
  </div>
</template>

<script>
export default {
  name: 'HomePage',
  data() {
    return {
      loading: false,
      appList: [],
      isDragging: false,
      uploadLoading: false,
      uploadProgress: 0,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      baseUrl: process.env.VUE_APP_BASE_API,
      deleteLoading: null
    }
  },
  created() {
    this.getUserInfo()
    
    
  },
  methods: {
    formatFileSize(bytes) {
      if (!bytes) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },
    formatDate(timestamp) {
      if (!timestamp) return '未知'
      const date = new Date(timestamp)
      return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
    },
    truncateText(text, length) {
      if (!text) return ''
      return text.length > length ? text.substring(0, length) + '...' : text
    },
    async fetchAppList(retryCount = 0) {
      if (!this.$api?.home?.getCardList) {
        this.$message.error('API方法未初始化')
        return
      }

      this.loading = true
      const userInfo = JSON.parse(localStorage.getItem('userInfo'))
      try {
        const res = await this.$api.home.getCardList({
          uid:userInfo.id,
          pageNum: this.currentPage,
          pageSize: this.pageSize
        })
        
        if (res?.code === '00000') {
          this.appList = res.data?.list || []
          this.total = res.data?.total || 0
        } else {
          throw new Error(res?.message || '获取数据失败')
        }
      } catch (err) {
        console.error('获取应用列表失败:', err)
        if (retryCount < 2) {
          await new Promise(resolve => setTimeout(resolve, 1000))
          return this.fetchAppList(retryCount + 1)
        }
        this.$message.error(err.message || '获取应用列表失败')
        this.appList = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },
    async getUserInfo(retryCount = 0){
      try{
        const res = await this.$api.user.getInfo({})

        if (res?.code === '00000'){
          localStorage.setItem('userInfo', JSON.stringify(res.data))
        }
        this.fetchAppList()
      }catch(err){
         if (err.status === 401){
        console.log('token过期')
          localStorage.removeItem('token')
          this.$router.push('/login')
      }
        console.error('获取应用列表失败:', err)
      }
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchAppList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchAppList()
    },
    handleLogout() {
      this.$api.user.logout().then(() => {
        localStorage.removeItem('token')
        this.$router.push('/login')
      })
    },
    handleDragOver() {
      this.isDragging = true
    },
    handleDragLeave() {
      this.isDragging = false
    },
    handleDrop(e) {
      this.isDragging = false
      const files = e.dataTransfer.files
      if (files.length > 0) {
        this.uploadFile(files[0])
      }
    },
    handleUpload({ file }) {
      this.uploadFile(file)
    },
    async uploadFile(file) {
      this.uploadLoading = true
      this.uploadProgress = 0
      try {
        const userInfo = JSON.parse(localStorage.getItem('userInfo'))
        if (!userInfo || !userInfo.id) {
          throw new Error('用户信息无效，请重新登录')
        } 

        const formData = new FormData()
        console.log(userInfo)
        formData.append('file', file)
        formData.append('uid', userInfo.id)
        formData.append('username', userInfo.username)
        formData.append('userRole', userInfo.role || 'user')
        
        await this.$api.home.uploadAppFile(formData)
        this.$message.success('上传成功')
        this.fetchAppList()
      } catch (err) {
        this.$message.error(err.message || '上传失败')
      } finally {
        this.uploadLoading = false
        this.uploadProgress = 0
      }
    },
    beforeUpload(file) {
      const isValidType = ['.apk', '.ipa', '.zip', '.rar'].some(type => 
        file.name.toLowerCase().endsWith(type)
      )
      if (!isValidType) {
        this.$message.error('只支持上传APK/IPA/ZIP/RAR格式文件')
        return false
      }
      return true
    },
    handleProgress(event) {
      this.uploadProgress = Math.floor(event.percent)
    },
    formatProgress(percentage) {
      return `上传中 ${percentage}%`
    },
     onSubmit(app) {
      const url = `${window.location.origin}/download?&shortCode=${app.shortCode}&pid=${app.pid}`
      window.open(url, '_blank')
    },
    
    async handleDelete(app) {
      try {
        this.deleteLoading = app.id
        await this.$api.home.deleteApp({ appId: app.id })
        this.$message.success('删除成功')
        this.fetchAppList()
      } catch (err) {
        this.$message.error(err.message || '删除失败')
      } finally {
        this.deleteLoading = null
      }
    }
  }
}
</script>

<style scoped>
.home-page {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.card-container {
  margin-top: 20px;
}

.app-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: transform 0.3s;
  height: 350px;
}

.app-card:hover {
  transform: translateY(-5px);
}

.app-icon {
  font-size: 50px;
  margin-bottom: 10px;
  color: #409EFF;
  text-align: center;
}

.app-icon img {
  width: 50px;
  height: 50px;
  border-radius: 8px;
}

.app-info {
  margin-top: 10px;
}

.app-name {
  font-weight: bold;
  font-size: 16px;
  text-align: center;
  margin-bottom: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.app-meta {
  font-size: 12px;
  color: #606266;
  line-height: 1.6;
}

.app-meta div {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.app-actions {
  margin-top: 10px;
  display: flex;
  justify-content: space-between;
}

.upload-card {
  margin-bottom: 20px;
  text-align: center;
  transition: transform 0.3s;
  background-color: #f0f7ff;
}

.upload-card:hover {
  transform: translateY(-5px);
}

.upload-content {
  padding: 20px;
}

.upload-text {
  margin: 10px 0;
}

.file-types {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.el-upload-dragger {
  width: 100%;
  height: auto;
  padding: 20px;
  border: none;
  background: transparent;
}

.el-upload-dragger:hover {
  border-color: #409EFF;
}

.el-progress {
  margin-top: 10px;
}

.upload-area {
  padding: 20px;
  color: #606266;
}

.upload-area i {
  font-size: 40px;
  color: #409EFF;
  margin-bottom: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}
</style>
